package com.utils;

import com.alibaba.fastjson.JSON;
import com.crmeb.core.exception.CrmebException;
import com.zbkj.crmeb.plat.by.dto.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.spi.ErrorCode;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;


@Component
public class PushPayToCustomsUtils {

    public static Result wChatPay(String appid, String mchId, String orderNo, String payNo, String customsNo, String carId, String carName, String key){
        Map<String,String> map = new HashMap<>();
        map.put("appid", appid);
        map.put("mch_id", mchId);
        map.put("out_trade_no",orderNo);
        map.put("transaction_id", payNo);
        map.put("action_type", "ADD");
//        map.put("action_type", "MODIFY");
        map.put("customs","HANGZHOU_ZS");
        map.put("mch_customs_no","3303960EZ4");
        if (StringUtils.isNotBlank(customsNo)){
            map.put("mch_customs_no", customsNo);
        }
        map.put("cert_type", "IDCARD");
        map.put("cert_id", carId);
        map.put("name", carName);

        String preSignStr = createLinkStringHttp(map);
        preSignStr += "&key="+key;
        String sign = MD5Util.MD5Encode(preSignStr).toUpperCase();

        StringBuffer buf = new StringBuffer();
        buf.append("<xml>");
        buf.append("<cert_id>"+carId+"</cert_id>");
        buf.append("<name>"+carName+"</name>");
        buf.append("<cert_type>IDCARD</cert_type>");
        buf.append("<appid>" + appid + "</appid>");
        buf.append("<customs>HANGZHOU_ZS</customs>");
        buf.append("<mch_customs_no>"+map.get("mch_customs_no")+"</mch_customs_no>");
        buf.append("<mch_id>" + mchId + "</mch_id>");
        buf.append("<out_trade_no>"+ orderNo +"</out_trade_no>");
        buf.append("<transaction_id>"+ payNo +"</transaction_id>");
        buf.append("<sign>"+sign+"</sign>");
        buf.append("<action_type>"+map.get("action_type")+"</action_type>");
        buf.append("</xml>");
        String result = null;
        try {
            result = getCustoms(buf.toString());
            System.out.println(result);
            Document document = DocumentHelper.parseText(result);
            Element root = document.getRootElement();
            String return_code = root.elementText("return_code");
            if (!(return_code.equals("SUCCESS")))
            {
                System.out.println(result);
                return Result.getFailureResult("验证信息错误","验证信息错误！");
            }
            @SuppressWarnings("unchecked")
            List<Element> elementList = root.elements();
            // 遍历所有子节点
            Map<String, String> mapData = new HashMap<String, String>();
            for (Element e : elementList)
            {
                mapData.put(e.getName(), e.getText());
            }
            if (!Objects.equals("成功",mapData.get("return_msg"))){
                return Result.getFailureResult("error", JSON.toJSONString(mapData));
            }
            String returnSign = mapData.get("sign");
            mapData.remove("sign");
            String returnPreSignStr = createLinkStringHttp(mapData);
            // 获取待签名字符串
            returnPreSignStr += "&key="+key;
            String _sign = MD5Util.MD5Encode(returnPreSignStr).toUpperCase();
            if (!_sign.equals(returnSign))
            {
                System.out.println("验证签名失败");
                return Result.getFailureResult("验证信息错误","验证信息错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.getSuccessResult();
    }
    public static String getCustoms(String xml) throws IOException
    {
        String urlStr = "https://api.mch.weixin.qq.com/cgi-bin/mch/customs/customdeclareorder";
        URL url = new URL(urlStr);
        URLConnection con = url.openConnection();
        con.setDoOutput(true);
        con.setRequestProperty("Cache-Control", "no-cache");
        con.setRequestProperty("Content-Type", "text/xml");

        OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), "utf-8");
        out.write(xml);
        out.flush();
        out.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String result = "";
        String line = "";
        for (line = br.readLine(); line != null; line = br.readLine())
        {
            result = result + line;
        }
        byte[] bs = result.getBytes();
        String sTotalString = new String(bs, "utf-8");
        return sTotalString;
    }
    public static String createLinkStringHttp(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }
}
